<template>
	<div class="layui-unselect layui-form-switch" :class="isOn ? 'layui-form-onswitch' : ''" lay-skin="_switch" @click="switchs">
		<em>{{isOn ? onText : offText}}</em><i></i>
	</div>
</template>

<script>
	import kit from "../common/kit.js" ;
	export default {
		name: "switchBtn",
		props: {
			onText : {
				type : String ,
				default : "ON"
			},
			offText : {
				type : String ,
				default : "OFF"
			},
			name : {
				type : String ,
				default : ""
			},
			value : {
				type : [Boolean,String,Number] ,
				default : true
			},
			url : { //切换时，请求的地址
				type : String ,
				default : ""
			}
		},
		
		computed:{
			
		},
		
		data() {
			return {
				isOn : !!this.value
			};
		},
		
		created() {
			this.setIsOnValue();
		},
		
		watch:{
			value : function(res){
				this.setIsOnValue();
			}
		},
		
		methods:{
			
			setIsOnValue:function(res){
				this.isOn = this.value == true || this.value == 'true' || this.value == 1 || this.value == "1" ;
				console.log(this.isOn , this.value);
			},
			
			switchs:function(e){
				if ( this.checkAuth() == false) {
					console.log("noAuth:" ,this.url);
					return false ;
				}
				var that = this ;
				var data = {} ;
				data[this.name] = !that.isOn ;
				kit.get( this.url ,data,function(res){
					that.$emit("change",res);
				});
			},
			
			checkAuth : function(){
				var url = this.url ;
				if (!this.url) {
					return false ;
				}
				var index = this.url.indexOf("?");
				if(index > -1){
					url = url.substr(0,index);
				}
				var menuList = getApp().globalData.menuList ;
				if (menuList.length == 0) {
					return false ;
				}
				for (var i = 0; i < menuList.length; i++) {
					var cur = menuList[i];
					if( (cur.url + ";").indexOf(url+";") > -1){
						return true ;
					}
				}
				console.log("noAuth:" + url);
				return false ;
			}
			
		}
	}
</script>

